//
//  ViewController.swift
//  weather
//
//  Created by smile on 2020/10/20.
//

import UIKit

//导入定位相关
import CoreLocation

//导入RxSwift
import RxSwift


//导入发布订阅
import SwiftEventBus

class ViewController: UIViewController {
    //负责对象销毁
    //这个功能类似NotificationCenter的removeObserver
    let disposeBag=DisposeBag()
    
    //列表控件
    @IBOutlet weak var collectionView: UICollectionView!
    
//    var currentLocation:CLLocation?
    
    var currentArea:Area?
    
    /// 当前界面列表数据
    var dataArray:[Area] = []
    
    var currentIndex = 0
    
    
    var locationManager:CLLocationManager!
    var geocoder:CLGeocoder!

    override func viewDidLoad() {
        super.viewDidLoad()
        //初始化列表控件
        
        //注册cell
        collectionView.register(WeatherCell.self, forCellWithReuseIdentifier: CELL)
        
        //定位服务是否启用
//        if (CLLocationManager.locationServicesEnabled()){
              //允许使用定位服务的话，开始定位服务更新
              locationManager = CLLocationManager()

            //大于该距离才回调，米
            locationManager.distanceFilter = 1000

            //精度 比如为10 就会尽量达到10米以内的精度，1000米
            locationManager.desiredAccuracy = kCLLocationAccuracyKilometer


              locationManager.delegate = self

              locationManager.desiredAccuracy = kCLLocationAccuracyBest

              locationManager.distanceFilter = 10

             locationManager.requestWhenInUseAuthorization()

              locationManager.startUpdatingLocation()
//           }
        
//        纬度:37.785834,纬度:122.406417,海拔:0.0
//        currentArea=Area()
//        currentArea!.name = "北京"
//
//        currentArea!.location = Location()
//        currentArea!.location.lat = 40.22077
//        currentArea!.location.lng = 116.23128
//        fetchData()
        
        //监听选择了地区
        SwiftEventBus.onMainThread(self, name: ON_SELECT_AREA) { (sender) in
            //获取发送过来的数据
            self.currentIndex = sender?.object as! Int
            
            if let _ = self.currentArea {
                //逆地理编码成功
                self.currentIndex += 1
            }
            
            self.fetchData()
        }
        
    }
    
    /// 加载首页数据
    func fetchData() {
        //移除原来数据
        dataArray.removeAll()
        
        //添加当前城市
        if let d = currentArea {
            dataArray.append(d)
        }

        //加载用户选择的城市
        if let d=PreferenceUtil.getAreas() {
            dataArray = dataArray + d
        }
        
        //设置标题
        navigationItem.title = dataArray[currentIndex].name
//
//        let area1 = Area()
//        area1.name = "北京"
//        area1.location = Location()
//        area1.location.lat = 40.22077
//        area1.location.lng = 116.23128
//
//        dataArray.append(area1)
//
//        let area2 = Area()
//        area2.name = "成都"
//        area2.location = Location()
//        area2.location.lat = 30.65984
//        area2.location.lng = 104.10194
//
//        dataArray.append(area2)
        
        //重新加载数据
        collectionView.reloadData()
        
        //获取当前定位城市数据
        fetchWeatherData(currentIndex)
        
        if (currentIndex != 0) {
            //跳转到当前位置
            collectionView.scrollToItem(at: IndexPath(row: currentIndex, section: 0), at: .left, animated: false)
        }
    }
    
    
    /// 开始逆地理编码
    /// - Parameter location: <#location description#>
    func startGeoLocation(_ location:CLLocation) {
        geocoder=CLGeocoder()
        
//        纬度:37.785834,纬度:122.406417,海拔:0.0
        //模拟器纬度是负数
//        let testLocation = CLLocation(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
        
        geocoder.reverseGeocodeLocation(location) { (placemarks, error) in
            if let _ = error{
                let alertController=UIAlertController(title: "地理位置解码失败", message: "请检查是否允许本应用获取当前位置，同时不要在模拟器运行本应用.", preferredStyle: .alert)
                
                let confirmAction=UIAlertAction(title: "确定", style: .default, handler: nil)

                    //将动作添加到控制器
                    alertController.addAction(confirmAction)
        //            alertController.addAction(cancelAction)

                    //显示
                self.present(alertController, animated: true, completion: nil)
            }else if let placemarks = placemarks,placemarks.count>0{
                //有数据
                let placemark = placemarks.first!
                
                //城市
                //参考：https://www.jianshu.com/p/e8c60de940f5
//                var city = placemark.locality
//                if city == nil {
//                    //四大直辖市的城市信息无法通过locality获得，只能通过获取省份的方法来获得（如果city为空，则可知为直辖市）
//                    city = placemark.administrativeArea
//                }
//
//                //区
//                let area = placemark.subLocality
//
//                print("startGeoLocation:城市:\(city),\(area)")
                
                //添加当前定位城市
                self.currentArea=Area()
                
                //黄陵街道
                self.currentArea!.name = placemark.name
                
                self.currentArea!.location = Location()
                self.currentArea!.location.lat = location.coordinate.latitude
                self.currentArea!.location.lng = location.coordinate.longitude
                
                self.fetchData()
            }
        }
        
    }


}


//定位代理
extension ViewController:CLLocationManagerDelegate{
    
    /// 位置更新，会一直回调，如果只需定位一次，获取到数据后停止
    /// - Parameters:
    ///   - manager: <#manager description#>
    ///   - locations: <#locations description#>
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        let currLocation : CLLocation = locations.last!  // 持续更新

//       let _:NSArray =  locations as NSArray
        
        //纬度
        let latitude=currLocation.coordinate.latitude
        
        //纬度
        let longitude=currLocation.coordinate.longitude
        
        //海拔
        let altitude=currLocation.altitude
        
        //例如：纬度:30.77066667843911,纬度:110.62777146331537,海拔:780.680009841919
       print("纬度:\(latitude),纬度:\(longitude),海拔:\(altitude)")
        
        //停止定位
        locationManager.stopUpdatingLocation()
        
        
        //开始逆地理编码
        startGeoLocation(currLocation)
    }
    
    
    /// 定位失败
    /// - Parameters:
    ///   - manager: <#manager description#>
    ///   - error: <#error description#>
    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print("didFailWithError:\(error)")
        
        let alertController=UIAlertController(title: "定位失败", message: "请在设置允许本应用获取当前位置才能显示当前位置天气.", preferredStyle: .alert)
        
        let confirmAction=UIAlertAction(title: "确定", style: .default, handler: nil)

            //将动作添加到控制器
            alertController.addAction(confirmAction)
//            alertController.addAction(cancelAction)

            //显示
            present(alertController, animated: true, completion: nil)
    }
}


// MARK: - 实现CollectionView数据源和代理
extension ViewController: UICollectionViewDataSource,UICollectionViewDelegate {
    
    /// 返回有多少个
    ///
    /// - Parameters:
    ///   - collectionView: <#collectionView description#>
    ///   - section: <#section description#>
    /// - Returns: <#return value description#>
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataArray.count
    }
    
    /// 返回当前位置Cell
    ///
    /// - Parameters:
    ///   - collectionView: <#collectionView description#>
    ///   - indexPath: <#indexPath description#>
    /// - Returns: <#return value description#>
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        //获取数据
        let data = dataArray[indexPath.row]
        
        //获取Cell
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CELL, for: indexPath)
            as! WeatherCell
        
        cell.tag = indexPath.row
        
        //设置下拉刷新回调方法
        cell.onRefresh = {
            data in
            print("CommentController onNicknameClick:\(data)")
            
            self.fetchWeatherData(data)
        }
        
        //显示数据
        cell.bindData(data)
        
        
        //返回cell
        return cell
    }
    
    
    /// 获取天气预报数据
    /// - Parameter data: <#data description#>
    func fetchWeatherData(_ data:Int) {
//        WeatherApi.shared.realtime(id)
//            .subscribeOnSuccess { (data) in
//            if let data=data?.data{
//                self.showData(data)
//            }
//        }.disposed(by: disposeBag)
        
        let currentArea = dataArray[data]
        
        WeatherApi.shared.weather(lat: currentArea.location.lat, lng: currentArea.location.lng).subscribe(onNext: { response in
            print("fetchWeatherData success:\(response)")
            
            self.showWeatchData(currentArea,response)
            
        }, onError: { data in
            self.showErrorAlert()
        }, onCompleted: nil, onDisposed: nil)

    }
    
    func showErrorAlert() {
        let alertController=UIAlertController(title: "错误提示", message: "网络请求失败，请检查网络，并稍后再试，如果还有问题请在设置联系我们反馈.", preferredStyle: .alert)
        
        let confirmAction=UIAlertAction(title: "确定", style: .default, handler: nil)

            //将动作添加到控制器
            alertController.addAction(confirmAction)

            //显示
            present(alertController, animated: true, completion: nil)
    }
    
    
    /// 显示天气数据
    /// - Parameters:
    ///   - area: <#area description#>
    ///   - realtime: <#realtime description#>
    func showWeatchData(_ area:Area,_ data:WeatherResponse) {
        if "ok" != data.status {
            showErrorAlert()
            return
        }
        
        //当前时间
//        area.updatedAt = Date.init()
        
        //天气信息
        area.weather = data.result
        
        //重新加载数据
        collectionView.reloadData()
    }
    
}

// MARK: - 实现UICollectionViewDelegateFlowLayout协议
extension ViewController: UICollectionViewDelegateFlowLayout {
    
    /// 返回Cell和CollectionView的间距
    ///
    /// - Parameters:
    ///   - collectionView: <#collectionView description#>
    ///   - collectionViewLayout: <#collectionViewLayout description#>
    ///   - section: <#section description#>
    /// - Returns: <#return value description#>
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
    }
    
    /// 返回每一行Cell间距
    ///
    /// - Parameters:
    ///   - collectionView: <#collectionView description#>
    ///   - collectionViewLayout: <#collectionViewLayout description#>
    ///   - section: <#section description#>
    /// - Returns: <#return value description#>
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }
    
    /// 返回每列Cell间距
    ///
    /// - Parameters:
    ///   - collectionView: <#collectionView description#>
    ///   - collectionViewLayout: <#collectionViewLayout description#>
    ///   - section: <#section description#>
    /// - Returns: <#return value description#>
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }
    
    /// 返回Cell大小
    ///
    /// - Parameters:
    ///   - collectionView: <#collectionView description#>
    ///   - collectionViewLayout: <#collectionViewLayout description#>
    ///   - indexPath: <#indexPath description#>
    /// - Returns: <#return value description#>
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        //让Cell和Collection一样大
        return collectionView.frame.size
    }
    
    /// 滚动结束（惯性滚动）
    ///
    /// - Parameter scrollView: <#scrollView description#>
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        //获取当前位置
        let currentIndex = Int(collectionView.contentOffset.x / collectionView.frame.width)
        
        print("ViewController scrollViewDidEndDecelerating:\(currentIndex),\(collectionView.contentOffset),")
        
        navigationItem.title = dataArray[currentIndex].name
        
        //TODO 大于三分钟才获取数据
        
        //获取数据
        fetchWeatherData(currentIndex)
    }
}
